package cn.tedu.charging.device.repository;

import cn.tedu.charging.common.pojo.po.ChargingGunInfoPO;
import cn.tedu.charging.common.pojo.po.ChargingStationPO;
import cn.tedu.charging.common.pojo.query.NearStationsQuery;
import cn.tedu.charging.device.mapper.GunMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class DeviceRepositoryImpl implements DeviceRepository{
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private GunMapper gunMapper;
    @Override
    public List<GeoResult> nearStations(NearStationsQuery query) {
        //1.组织一个查询范围的数据 包括 中心点 Point center 半径距离 radius 单位km
        //2.withdist withcoord
        //3.georadius beijing_stations centerLng centerLat radius km withdist withcoord
        String key="beijing_stations";
        Point center=new Point(query.getLongitude(),query.getLatitude());
        Distance radius=new Distance(query.getRadius(), RedisGeoCommands.DistanceUnit.KILOMETERS);
        Circle circle=new Circle(center,radius);
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
                .includeDistance()//withdist
                .includeCoordinates();//withcoord
        GeoResults geoResults =
                redisTemplate.opsForGeo().radius(key, circle,args);

        return geoResults.getContent();
    }

    @Override
    public String getStationName(Integer stationId) {
        //组织一个缓存查询逻辑 缓存查询 命中则返回 没命中 查数据库
        String stationKey="charging:station:cache:"+stationId;
        ChargingStationPO po= (ChargingStationPO) redisTemplate.opsForValue().get(stationKey);
        //判断非空
        String stationName="";
        if(po!=null){
            stationName=po.getStationName();
        }
        return stationName;
    }

    @Override
    public ChargingStationPO getStationById(Integer stationId) {
        //组织一个缓存查询逻辑 缓存查询 命中则返回 没命中 查数据库
        String stationKey="charging:station:cache:"+stationId;
        ChargingStationPO po= (ChargingStationPO) redisTemplate.opsForValue().get(stationKey);
        return po;
    }

    @Override
    public List<ChargingGunInfoPO> getGunListByStationId(Integer stationId) {
        //枪是否可以放到缓存里
        //枪数据放到缓存中,会导致枪状态变动,缓存经常进行修改 清空
        return gunMapper.selectByStationId(stationId);
    }
}